//
//  NISecurityPasswordViewController.m
//  gweAD
//
//  Created by navinfo air on 2016/12/5.
//  Copyright © 2016年 mengy. All rights reserved.
//

#import "NISecurityPasswordViewController.h"
#import "TagDefines.h"
#import "NIGestureLockView.h"
#import "MainViewController.h"
#import "AppContext.h"
#import "UserDefaultsKeyDefine.h"
#import "SecurityCenterViewModel.h"
#import "NIBiometricsView.h"

@interface NISecurityPasswordViewController ()<NIBiometricsViewDelegate>

@end

@implementation NISecurityPasswordViewController{
    NISecurityPasswordView *securityPasswordView;
    //防止指纹验证期间连续多次点击
    UIView *clearView;
    
    //临时数据
    NSString *lastPassword;
    
    BOOL forgotButtonClicked;
    
    NIGestureLockView *gesturelockView;
    NIBiometricsView *biometricsView;
    
    SecurityCenterViewModel *securityCenterViewModel;
    
    BOOL forceHiddenChangeButton;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (!securityPasswordView.hidden) {
        [securityPasswordView showKeyBoard];
    }else{
        [securityPasswordView closeKeyBoard];
    }
    securityCenterViewModel = [[SecurityCenterViewModel alloc] init];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillChangeStatusBarFrameNotification:)
                                                 name:UIApplicationDidChangeStatusBarFrameNotification
                                               object:nil];
    /*
    if (forgotButtonClicked && !forceHiddenChangeButton) {
        forgotButtonClicked = NO;
//        if (_controller.canSetUpSecurityPasswordAndLicenseNumber && !_controller.isSecurityPasswordSetUp){
//            return;
//        }
        [securityPasswordView setHidden:NO];
    }
     */
}

- (void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self  name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    [super viewWillDisappear:animated];
    [securityPasswordView clearPassword];
}

- (void)appWillChangeStatusBarFrameNotification:(id)sender{
    CGRect rect = [[UIApplication sharedApplication] statusBarFrame];
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    CGRect passwordViewFrame = securityPasswordView.frame;
    passwordViewFrame.origin.y = rect.size.height;
    passwordViewFrame.size.height = window.bounds.size.height - rect.size.height;
    securityPasswordView.frame = passwordViewFrame;
}

-(void)viewDidBack{
    [super viewDidBack];
    if (!securityPasswordView.hidden) {
        securityPasswordView.hidden = YES;
        [securityPasswordView removeFromSuperview];
        [clearView removeFromSuperview];
    }
//    self.controller.securityPasswordDataSource = nil;
}

- (void)enableSecurityPassword{
    if(securityPasswordView){
        return;
    }
    CGRect rect = [[UIApplication sharedApplication] statusBarFrame];
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    securityPasswordView = [[NISecurityPasswordView alloc] initWithFrame:CGRectMake(0, rect.size.height, self.view.frame.size.width, window.bounds.size.height - rect.size.height)];
    securityPasswordView.delegate = self;
    securityPasswordView.hidden = YES;
    [[[UIApplication sharedApplication] keyWindow] addSubview:securityPasswordView];
    [securityPasswordView setTag:TAG_SECURITYPASSWORDINWINDOW];
    
    //
    gesturelockView = [[NIGestureLockView alloc] initWithFrame:CGRectMake(0, rect.size.height, self.view.frame.size.width, window.bounds.size.height - rect.size.height)];
    gesturelockView.delegate = self;
    
    biometricsView = [[NIBiometricsView alloc] initWithFrame:CGRectMake(0, rect.size.height, self.view.frame.size.width, window.bounds.size.height - rect.size.height)];
    biometricsView.delegate = self;
    
    [[[UIApplication sharedApplication] keyWindow] addSubview:gesturelockView];
    [gesturelockView setTag:TAG_GESTURELOCKINWINDOW];
    gesturelockView.hidden = YES;
    
    
    [[[UIApplication sharedApplication] keyWindow] addSubview:biometricsView];
    [biometricsView setTag:TAG_BIOMETRICELOCKINWINDOW];
    biometricsView.hidden = YES;
    
    clearView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [clearView setBackgroundColor:[UIColor clearColor]];
    [[[UIApplication sharedApplication] keyWindow] addSubview:clearView];
    [clearView setTag:TAG_SECURITYPASSWORDBGINWINDOW];
    clearView.hidden = YES;
    
    NSArray *viewTags = @[@TAG_NOTIFICATIONINWINDOW,@TAG_MENUINWINDOW,@TAG_SECURITYPASSWORDINWINDOW,@TAG_SECURITYPASSWORDBGINWINDOW,@TAG_LOADINGINWINDOW];
    NSNumber *number;
    for (int i = 0; i < viewTags.count; i++) {
        number = [viewTags objectAtIndex:i];
        if ([window viewWithTag:number.integerValue]) {
            [window bringSubviewToFront:[window viewWithTag:number.integerValue]];
        }
    }
}


- (void)validateSecurityPassword{
    BOOL hidden = (![securityCenterViewModel isGestureLockSetup] && ![securityCenterViewModel isBiometricsLockSetup]) || forceHiddenChangeButton;
    [securityPasswordView hiddenChangeButton:hidden];
    [gesturelockView hiddenChangeButton:hidden];
    
    //是否设置安全密码
    if(![securityCenterViewModel isSecurityPasswordSetUp]){
        [self toSettingPassword];
        return;
        UIAlertController *c = [UIAlertController alertControllerWithTitle:nil message:@"请设置安全密码" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *logoutAction = [UIAlertAction actionWithTitle:@"稍后" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *settingAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self toSettingPassword];
        }];
        [c addAction:logoutAction];
        [c addAction:settingAction];
        [self presentViewController:c animated:YES completion:nil];
        return;
    }

    
    //获取保存的验证方式 同时判断是否支持对应方式
    ValidateSecurityWay validateWay;
    if (self.validateSecurityWay > 0) {
        validateWay = self.validateSecurityWay;
    }else{
        validateWay = [securityCenterViewModel getValidateSecurityWay];
    }
    if (validateWay == ValidateSecurityWayBiometrics && [self isLocalAuthenticationAble] != 0) {
        validateWay = ValidateSecurityWayPassword;
        [securityCenterViewModel setValidateSecurityWay:ValidateSecurityWayPassword];
    }
    if (validateWay == ValidateSecurityWayGesture && ![securityCenterViewModel isGestureLockSetup]) {
        validateWay = ValidateSecurityWayPassword;
    }
    if (validateWay == ValidateSecurityWayBiometrics && ![securityCenterViewModel isBiometricsLockSetup]) {
        validateWay = ValidateSecurityWayPassword;
    }
    
    if (validateWay == ValidateSecurityWayNone) {
        validateWay = ValidateSecurityWayPassword;
    }
    self.validateSecurityWay = ValidateSecurityWayNone;
    
    switch (validateWay) {
        case ValidateSecurityWayPassword:
            [securityPasswordView setHidden:NO];
            clearView.hidden = YES;
            break;
        case ValidateSecurityWayGesture:
            [gesturelockView setHidden:NO];
            clearView.hidden = YES;
            break;
        case ValidateSecurityWayBiometrics:
            if(![self policyLocalAuthenticationWithBiometrics]){
                //显示安全密码界面
                [securityPasswordView setHidden:NO];
                clearView.hidden = YES;
            }
            else
            {
                
                [biometricsView setHidden:NO];
            }
            break;
            
        default:
            break;
    }
}

- (void)onActionClick{
    [securityPasswordView setHidden:NO];
    clearView.hidden = YES;
}

#pragma mark - RemoteControlBusinessControllerDataSource

- (NSString *)scyPwd4SecurityPasswordBusinessController{
    return lastPassword;
}

- (NSString *)signStr4SecurityPasswordBusinessController{
//    AppContext *appContext = [AppContext getInstance];
//    return [NSString stringWithFormat:@"%@%@",appContext.vehicleModel.vin, appContext.userModel.userToken];
    return @"";
}


-(NSString *)userType4NewSecurityPasswordBusinessController{
//    return [AppContext getInstance].vehicleModel.ownership;
    return @"";
}


#pragma mark - LocalAuthenticationViewController
- (void)localAuthenticationSuccess{
    //处理业务
    clearView.hidden = YES;
}

- (void)localAuthenticationCancel{
    [self showAlertWithActionTitle:@"更改密码输入方式" ActionTitle:@"使用安全密码"];
    clearView.hidden = YES;
}

- (void)localAuthenticationSystemCancel{
    [self showAlertWithActionTitle:@"确定要退出吗" ActionTitle:@"使用安全密码" cancelActionTitle:@"确定"];
    clearView.hidden = YES;
}

- (void)localAuthenticationFailed{
    [securityPasswordView setHidden:NO];
    clearView.hidden = YES;
}

- (void)gestureDidInputFinish:(NSString *)password{
    
}

- (void)clearGestureLockView{
    [gesturelockView clearView];
}

- (void)forceHiddenChangeButton:(BOOL)hidden{
    forceHiddenChangeButton = hidden;
    [gesturelockView hiddenChangeButton:hidden];
    [securityPasswordView hiddenChangeButton:hidden];
}

-(void)cancelChangePasswordAlert
{
    
}

#pragma mark - NIBiometricsViewDelegate
-(void)biometricsChangeButtonDidClick
{
    [self changeButtonDidClick];
}

-(void)biometricsAuthButtonDidClick
{
    [self validateSecurityPassword];
}

#pragma mark - NISecurityPasswordView
- (void)passwordDidInputFinish:(NSString *)password{
    lastPassword = password;
    //处理业务
    
}
- (void)viewWillClose{
    
}

- (void)forgotButtonDidClick{
//    if (DEMO_WORKING) {
//        [securityPasswordView setHidden:YES];
//        clearView.hidden = YES;
//        [self showToast:@"您当前为体验模式，请使用正式帐号登录"];
//        return;
//    }
    forgotButtonClicked = YES;
    
        MainViewController *mainViewController = (MainViewController *)[self findViewControllerWithClass:[MainViewController class]];
        if (mainViewController) {
            [mainViewController toForgotPasswordViewController];
        }
    
    
}


-(void)toSettingPassword
{
    MainViewController *mainViewController = (MainViewController *)[self findViewControllerWithClass:[MainViewController class]];
    if (mainViewController) {
        [mainViewController toSettingPasswordViewController];
    }
}

- (void)gestureForgotButtonDidClick{
    self.validateSecurityWay = ValidateSecurityWayPassword;
    [self validateSecurityPassword];
    forgotButtonClicked = YES;
}

- (void)changeButtonDidClick{
    [securityPasswordView setHidden:YES];
    [gesturelockView setHidden:YES];
    [biometricsView setHidden:YES];
    UIAlertController *c = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self cancelChangePasswordAlert];
    }];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"口令密码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [securityCenterViewModel setValidateSecurityWay:ValidateSecurityWayPassword];
        [securityPasswordView setHidden:NO];
    }];
    [c addAction:action];
    
    if ([securityCenterViewModel isBiometricsLockSetup]) {
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"指纹密码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [biometricsView setHidden:NO];
            [securityCenterViewModel setValidateSecurityWay:ValidateSecurityWayBiometrics];
            [self validateSecurityPassword];
        }];
        [c addAction:action2];
    }
    
    if ([securityCenterViewModel isGestureLockSetup]) {
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"手势密码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [gesturelockView setHidden:NO];
            [securityCenterViewModel setValidateSecurityWay:ValidateSecurityWayGesture];
        }];
        [c addAction:action3];
    }
    [c addAction:cancelAction];
    
    [self presentViewController:c animated:YES completion:nil];
}

- (void)closeSecurityPasswordView{
    [securityPasswordView setHidden:YES];
    [gesturelockView setHidden:YES];
    [biometricsView setHidden:YES];
}

@end
